package com.haulmont.asu.web.ui.diploma_leader;

import com.haulmont.asu.entity.CorporationPresenter;
import com.haulmont.asu.entity.DiplomaLeader;
import com.haulmont.asu.entity.DiplomaProject;
import com.haulmont.cuba.gui.WindowManager;
import com.haulmont.cuba.gui.components.AbstractEditor;
import com.haulmont.cuba.gui.components.Component;
import com.haulmont.cuba.gui.components.Table;
import com.haulmont.cuba.gui.components.actions.CreateAction;
import com.haulmont.cuba.gui.data.CollectionDatasource;

import javax.inject.Inject;
import java.util.Collection;
import java.util.UUID;

/**
 * Author: Sergey42
 * Date: 09.11.13 7:40
 */
public class DiplomaLeaderEditor extends AbstractEditor<DiplomaLeader> {

    @Inject
    protected Table projectsTable;

    @Inject
    protected CollectionDatasource<DiplomaProject, UUID> projectsDs;

    @Override
    protected void postInit() {
        projectsTable.removeAction(projectsTable.getAction("create"));
        projectsTable.addAction(new CreateAction(projectsTable) {
            @Override
            public void actionPerform(Component component) {

                openLookup("ext$DiplomaProject.lookup", new Lookup.Handler() {
                    @Override
                    public void handleLookup(Collection items) {
                        for (Object item : items) {
                            DiplomaProject diplomaProject = (DiplomaProject) item;
                            if (!projectsDs.getItemIds().contains(diplomaProject.getId())) {
                                projectsDs.addItem(diplomaProject);
                            }
                        }
                    }
                }, WindowManager.OpenType.NEW_TAB);
            }
        });
    }

    @Override
    protected boolean preCommit() {
        DiplomaLeader leader = getItem();
        if (leader.getPerson() instanceof CorporationPresenter) {
            leader.setIsCathedral(false);
        }
        return true;
    }
}
